#import "LyricsController.h"

@implementation LyricsController

- (IBAction)getLyrics:(id)sender
{
}

- (IBAction)getSongName:(id)sender
{
	NSAppleScript* assong=[[NSAppleScript alloc] initWithSource:@"tell application \"iTunes\"\nset currentTrack to current track\nset info to {name:name of currentTrack, artist:artist of currentTrack, lyrics:lyrics of currentTrack, album:album of currentTrack}\nreturn info\nend tell"];
	
	NSAppleEventDescriptor	*aResult=[assong executeAndReturnError:nil];
	NSDictionary		*anInfo=[NSDictionary dictionaryWithObjectsAndKeys:
		[[aResult descriptorForKeyword:'pnam'] stringValue],@"Name",
		[[aResult descriptorForKeyword:'pArt'] stringValue],@"Artist",
		[[aResult descriptorForKeyword:'pLyr'] stringValue],@"Lyrics",
		[[aResult descriptorForKeyword:'pAlb'] stringValue],@"Album",
		nil];
	name=[anInfo objectForKey:@"Name"];
	artist=[anInfo objectForKey:@"Artist"];
	lyrics=[anInfo objectForKey:@"Lyrics"];
	if(name!=nil){
		[tbName setStringValue:name];		
	}
	if(artist!=nil){
		[tbArtist setStringValue:artist];		
	}
	if(lyrics!=nil){
		[tbLyrics setStringValue:lyrics];
	}else{
		lyrics=@"";
	}
	
	if(name!=nil && name!=@""){
		
		char* buffer=(char*)malloc(1024*4);
		char* nn=(char*)malloc(512);
	//	[name getCString:nn];
		//[name getCString:nn maxLength:512 encoding:NSUTF8StringEncoding];
		
		//[self encodeStr:nn];
		
		//int n=sprintf(buffer,"http://mp3.baidu.com/m?f=ms&rn=10&tn=baidump3lyric&ct=150994944&word=%s",nn);
		//int n=swprintf(buffer,"http://www.xuecs.com/lyrics.php?name=%s",nn);
		NSMutableString *ms=[NSMutableString stringWithString:@"http://www.xuecs.com/lyrics.php?name="];
		[ms appendString:name];
		/*
		char* strartist=(char*)malloc(512);
		[artist getCString:strartist];
		int n=swprintf(buffer,"http://xuecs.com/lyrics.php?name=%s&artist=%s",nn,strartist);
		 */
		//NSString* urlText=[NSString stringWithFormat:@"http://xuecs.com/lyrics.php?name=%s&artist=%s",name,""];
		//NSString* urlText=[NSString stringWithFormat:@"http://xuecs.com/lyrics.php?name=%s&artist=%s",name,@""];
		//NSString* urlText=[NSString stringWithFormat:@"http://localhost/lyrics.php?name=%s&artist=%s",name,@""];
		//NSString* urlText=[NSString stringWithCString:buffer encoding:NSUTF8StringEncoding];
		[ms getCString:buffer maxLength:1024*4 encoding:NSUTF8StringEncoding];
		NSString* urlText=[NSString stringWithUTF8String:buffer];
		
			//NSString* urlText=[NSString stringWithCString:buffer];	
		//urlText=@"http://www.xuecs.com";
		NSLog(urlText);
		NSString* goodUrl=[urlText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
		//NSString* goodUrl=[urlText stringByAddingPercentEscapesUsingEncoding:NSUnicodeStringEncoding];
		//NSString* goodUrl=[urlText stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
		NSLog(goodUrl);

		[[webView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:goodUrl]]];
	}
}

-(void)encodeStr:(char*)nn{
	char* ss=nn;
	while(ss!='\0' && ss-nn<512){
		if(*ss==' '){
			//move back 2				
			char* nx=ss+3;
			char n1=*(nx-2),n2=*(nx-1);
			while(*nx!='\0'){
				char n11=*nx;
				char n12=*(nx+1);
				*nx=n1;
				*(nx+1)=n2;
				n1=n11;
				n2=n12;
				nx+=2;
			}
			*nx=n1;
			*(nx+1)=n2;
			*(nx+2)='\0';
			
			*ss++ = '%';
			*ss++='2';
			*ss='0';
		}
		ss++;
	}
}

- (IBAction)selectLyrics:(id)sender
{
}

-(void)InitPasteboard{
	
	pb = [NSPasteboard pasteboardWithName:NSGeneralPboard]; 
	NSArray* types=[NSArray arrayWithObject:NSStringPboardType]; 
	[pb declareTypes:types owner:self];
	if(pb==nil){
		NSLog(@"can't get pasteboard\n");
		return;
	}
}
- (IBAction)setLyrics:(id)sender
{
	lyrics=[tbLyrics stringValue];
	
	//NSPasteboard *pb = [NSPasteboard pasteboardWithUniqueName]; 
	[self InitPasteboard];
	if(pb==nil){		
		return;
	}
		
	bool success = [pb setString:lyrics forType:NSStringPboardType]; 
    if (!success) { // very unlikely! 
        NSBeep(); 
    }else{
		NSLog( [pb name]);
	}
	
	//[self setLyricsFromClipboard:self];
	[self execScript:@"it"];
	//[self getSongName:nil];
}



- (IBAction)setLyricsFromClipboard:(id)sender{
	[self InitPasteboard];
	
	NSData* txt=[pb stringForType:NSRTFPboardType];
	
	if(txt!=nil){
		[tbLyrics setStringValue:txt];
		[self setLyrics:nil];
	}
	else
		return nil;

//	NSAppleScript* assong=[[NSAppleScript alloc] initWithSource:@"tell application \"iTunes\"\nset currentTrack to current track\n set txt to Unicode text of (the clipboard as record)\n set currentTrack's lyrics to txt  \nend tell"];
	/*
	[self InitPasteboard];
		
	NSBundle* mb=[NSBundle mainBundle];
	NSMutableString* path=[NSMutableString stringWithString:[mb resourcePath] ];
	[path appendString:@"/it.scpt"];
	NSString* scpt=[[NSString alloc] initWithContentsOfFile:path ];
	NSLog(scpt);
	
	NSDictionary* dict=[[NSDictionary alloc] init];
	NSAppleScript* assong=[ [NSAppleScript alloc] initWithSource:scpt];
	[assong compileAndReturnError:dict];
	NSLog([assong source]);
	//NSLog([assong isCompiled]);
	
																//error:<#(NSDictionary * *)errorInfo#>
	//NSAppleScript* assong=[[NSAppleScript alloc] initWithSource:@"tell application \"iTunes\"\n 	try\n 		\n 		set txt to (the clipboard as text)\n 	on error\n 		try\n 			set txt to <<class ktxt>> of ((the clipboard as text) as record)\n 		on error err_msg\n 			display dialog err_msg\n 		end try\n 	end try\n 	set ct to current track\n 	set ct's lyrics to txt\n end tell\n "];
	NSAppleEventDescriptor	*aResult=[assong executeAndReturnError:dict];
	if(aResult==nil)
		NSLog(@"script returnd nil");
	else{
		NSLog([aResult stringValue]);
	}
	 */
		
}

- execScript:(NSString*)name
{
    // load the script from a resource by fetching its URL from within our bundle
    NSString* path = [[NSBundle mainBundle] pathForResource:name ofType:@"scpt"];
    if (path != nil)
    {
        NSURL* url = [NSURL fileURLWithPath:path];
        if (url != nil)
        {
            NSDictionary* errors = [NSDictionary dictionary];
            NSAppleScript* appleScript =
				[[NSAppleScript alloc] initWithContentsOfURL:url error:&errors];
            if (appleScript != nil)
            {
                // create the first parameter
                NSAppleEventDescriptor* firstParameter =
				[NSAppleEventDescriptor descriptorWithString:@"Message from my app."];
				
                // create and populate the list of parameters (in our case just one)
                NSAppleEventDescriptor* parameters = [NSAppleEventDescriptor listDescriptor];
                [parameters insertDescriptor:firstParameter atIndex:1];
				
                // create the AppleEvent target
                ProcessSerialNumber psn = {0, kCurrentProcess};
                NSAppleEventDescriptor* target =
					[NSAppleEventDescriptor
                        descriptorWithDescriptorType:typeProcessSerialNumber
											   bytes:&psn
											  length:sizeof(ProcessSerialNumber)];
				
				/*
                // create an NSAppleEventDescriptor with the script's method name to call,
                // this is used for the script statement: "on show_message(user_message)"
                // Note that the routine name must be in lower case.
                NSAppleEventDescriptor* handler =
					[NSAppleEventDescriptor descriptorWithString:
                        [@"show_message" lowercaseString]];
				
                // create the event for an AppleScript subroutine,
                // set the method name and the list of parameters
                NSAppleEventDescriptor* event =
					[NSAppleEventDescriptor appleEventWithEventClass:kASAppleScriptSuite
															 eventID:kASSubroutineEvent
													targetDescriptor:target
															returnID:kAutoGenerateReturnID
													   transactionID:kAnyTransactionID];
                [event setParamDescriptor:handler forKeyword:keyASSubroutineName];
                [event setParamDescriptor:parameters forKeyword:keyDirectObject];
				
                // call the event in AppleScript
                if (![appleScript executeAppleEvent:event error:&errors]);
                {
                    // report any errors from 'errors'
                }
				*/
				[appleScript executeAndReturnError:nil];
                [appleScript release];
            }
            else
            {
                // report any errors from 'errors'
            }
        }
    }
}

- (IBAction)nextSong:(id)sender{
	[self execScript:@"next"];
	[self getSongName:nil];
}
- (IBAction)previousSong:(id)sender{
	[self execScript:@"pre"];
	[self getSongName:nil];
}
@end
